package com.jenings.shop.controller;

import com.jenings.shop.file.FastDFSFile;
import com.jenings.shop.util.FastDFSClient;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.io.FilenameUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

@Api(tags = {"文件上传"})
@RestController
public class UploadController {

    @ApiOperation(value = "文件名为File", notes="文件名为File")
    @PostMapping(value = "/upload",consumes = "multipart/*",headers = "content-type=multipart/form-date")
    public String upload(@RequestParam(value = "File")MultipartFile file) throws Exception {
        // 1、将附件属性信息封装到pojo
        String name = file.getOriginalFilename();       // 原始名称，1.jpg
        byte[] content = file.getBytes();               // 附件内容
        String ext = FilenameUtils.getExtension(name);  // 附件扩展名称
        String md5 = "xxx";
        String author = "zhangsan";
        FastDFSFile fastDFSFile = new FastDFSFile(name, content, ext, md5, author);
        // 2、调用文件上传方法
        String[] uploadResult = FastDFSClient.uploadFile(fastDFSFile);
        // 3、拼接图片的url地址
        String url = FastDFSClient.getUrl();
        url = url + "/" + uploadResult[0] + "/" + uploadResult[1];
        return url;
    }
}
